#define _CRT_SECURE_NO_WARNINGS 1
#include "queue.h"

void QueueInit(Node* q)
{
	assert(q);
	q->head = NULL;
	q->end = NULL;
}

bool QueueEmpty(Node* q)
{
	return q->head == NULL;
}

void QueuePush(Node* q, SDataType x)
{
	Queue* NewNode = (Queue*)malloc(sizeof(Queue));
	if (NewNode == NULL)
	{
		perror("malloc");
		exit(-1);
	}

	NewNode->data = x;
	NewNode->next = NULL;

	if (q->head == NULL)
	{
		q->head = q->end = NewNode;
	}
	else
	{
		q->end->next = NewNode;
		q->end = NewNode;
	}
}


void QueuePop(Node* q)
{
	assert(q);
	assert(!QueueEmpty(q));
	Queue* cur = q->head;
	q->head = cur->next;
	free(cur);
	cur = NULL;

	if (q->head == NULL)
	{
		q->end = NULL;
	}
}
SDataType QueueFront(Node* q)
{
	assert(q);
	assert(!QueueEmpty(q));

	return q->head->data;
}
SDataType QueueBack(Node* q)
{
	assert(q);
	assert(!QueueEmpty(q));

	return q->end->data;
}
int QueueSize(Node* q)
{
	assert(q);

	int len = 0;
	Queue* begin = q->head;
	while (begin)
	{
		++len;
		begin = begin->next;
	}

	return len;
}
void QueueDestroy(Node* q)
{
	assert(q);

	while (q->head)
	{
		Queue* begin = q->head;
		q->head = begin->next;
		free(begin);
	}

	q->head = q->end = NULL;
}